package com.chaoyong.higo.cainiaowo;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.interpolator;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chaoyong.higo.R;
import com.chaoyong.higo.activity.LoginActivity;
import com.chaoyong.higo.activity.PayActivity;
import com.chaoyong.higo.bean.DemoBean;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.EmptyUtil;
import com.chaoyong.higo.utils.JLog;
import com.chaoyong.higo.utils.PrefUtils;
import com.chaoyong.higo.utils.Values;
import com.chaoyong.higo.view.BadgeView;
import com.chaoyong.higo.view.CarNumberDialog;
import com.chaoyong.higo.view.ConfirmDialog;
import com.chaoyong.higo.view.ConfirmDialog.ClickListenerInterface;
import com.chaoyong.higo.view.NumberAddSubView;
import com.chaoyong.higo.view.NumberAddSubView.OnTextClickListener;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.connect.common.UIListenerManager.ApiTask;

public class CartAdapter extends SimpleAdapter<ShoppingCart>
		implements com.chaoyong.higo.cainiaowo.BaseRecyclerAdapter.OnItemClickListener {

	private TextView total_price, goods_counts;
	private CheckBox checkBox;
	
	private ImageView shop_trash,cfragshop_null;

	private CartProvider cartProvider;

	private LinearLayout ll;

	private List<String> jsonlist = new ArrayList<>();

	private String uid = "";
	
	private BadgeView badgeView;
	private Context context;
	

	public CartAdapter(Context context, List<ShoppingCart> datas, final CheckBox checkBox, TextView tv,
			LinearLayout ll, TextView goods_counts, ImageView cfragshop_null, BadgeView badgeView) {
		super(context, R.layout.item_shop, datas);

		setCheckBox(checkBox);
		setTextView(tv);

		this.badgeView = badgeView;
		
		cartProvider = new CartProvider(context);
		this.ll = ll;
		this.context = context;
		this.goods_counts = goods_counts;
		this.cfragshop_null = cfragshop_null;
		//setOnItemClickListener(this);

		showTotalPrice();
		
		
	}

	@Override
	protected void convert(final BaseRViewHolder viewHolder, final ShoppingCart item) {
		viewHolder.getTextView(R.id.txt_goods_name).setText("(第" + item.getExpect() + context.getResources().getString(R.string.expect) + ")" + item.getGoods_name());
		// Toast.makeText(context, item.getGoods_name(),
		// Toast.LENGTH_SHORT).show();
		
		shop_trash = viewHolder.getImageView(R.id.shop_trash);
		
		shop_trash.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				final ConfirmDialog confirmDialog = new ConfirmDialog(context, "确定删除？", "确定", "取消");
				confirmDialog.show();
				confirmDialog.setCancelable(false);
				confirmDialog.setClicklistener(new ClickListenerInterface() {
					
					@Override
					public void doConfirm() {
						item.setIsChecked(true);  
						delCart();
						Values.scno -= item.getCount();
						//badgeView.decrement(item.getCount());
						if(badgeView.getBadgeCount() != 0){
							badgeView.decrement(1);
						}
						Values.idList.remove(item.getGoods_id());
						showTotalPrice();
						confirmDialog.dismiss();
					}
					
					@Override
					public void doCancel() {
						// TODO Auto-generated method stub
						confirmDialog.dismiss();
					}
				});
				
			}
		});
		
		viewHolder.getTextView(R.id.txt_price).setText(item.getCount() + "");
		List<String> uri = item.getFace_img();
		String uri2 = item.getCover_img();
		/*ImageLoader.getInstance().displayImage(Values.BASE_IMAGE_URL + uri.get(0),
				viewHolder.getImageView(R.id.cart_g_image));*/
		
		if(uri != null){
			ImageLoader.getInstance().displayImage(Values.BASE_IMAGE_URL + uri.get(0),
					viewHolder.getImageView(R.id.cart_g_image));
		}else if(uri2 != null){
			ImageLoader.getInstance().displayImage(Values.BASE_IMAGE_URL + item.getCover_img().split("\\|")[0],
					viewHolder.getImageView(R.id.cart_g_image));
		}
		
		TextView tv = viewHolder.getTextView(R.id.shengyurenci);
		final int shengyu = item.getGoods_price().intValue() - item.getSurplus();
		tv.setText(shengyu + "");

		CheckBox checkBox = (CheckBox) viewHolder.getView(R.id.checkbox);
		checkBox.setChecked(item.isChecked());

		NumberAddSubView numberAddSubView = (NumberAddSubView) viewHolder.getView(R.id.num_control);
		if (item.getCount() == 0) {
			numberAddSubView.setValue(1);
		} else if (item.getCount() > 0) {
			numberAddSubView.setValue(item.getCount());
		}

		numberAddSubView.setMaxValue(shengyu);
		numberAddSubView.setOnButtonClickListener(new NumberAddSubView.OnButtonClickListener() {

			// 减法
			@Override
			public void onButtonSubClick(View view, int value, TextView mEtxtNum) {
				viewHolder.getTextView(R.id.txt_price).setText(value + "");
				item.setCount(value);
				// Toast.makeText(context, item.getCount() + "",
				// Toast.LENGTH_SHORT).show();
				cartProvider.update(item);
				showTotalPrice();
			}

			// 加法
			@Override
			public void onButtonAddClick(View view, int value, TextView mEtxtNum) {
				//viewHolder.getTextView(R.id.txt_price).setText(value + "");
				// Toast.makeText(context, item.getCount() + "",
				// Toast.LENGTH_SHORT).show();
				//Toast.makeText(context, "id = " +item.getGoods_id(), 0).show();
				addShoppingCart(item.getGoods_id(), item.getExpect(), item,value,viewHolder,mEtxtNum, shengyu);
				/*item.setCount(value);
				cartProvider.update(item);
				showTotalPrice();*/
			}
		});
		
		
		numberAddSubView.setOnTextClickListener(new OnTextClickListener() {

			@Override
			public void onTextClickLIstener(View view, int value,
					final TextView mEtxtNum) {
				// TODO Auto-generated method stub
				final CarNumberDialog carNumberDialog = new CarNumberDialog(context, "请输入要购买的份数", "确定", "取消", item.getCount() + "");
				carNumberDialog.show();
				carNumberDialog.setCancelable(false);
				carNumberDialog.setClicklistener(new CarNumberDialog.ClickListenerInterface() {
					
					@Override
					public void doConfirm(EditText etNumber) {
						// TODO Auto-generated method stub
						String number = etNumber.getText().toString();
						//Toast.makeText(context,  number, 0).show();
						if(TextUtils.isEmpty(number)){
							//Toast.makeText(context,  "请输入购买份数", 0).show();
							etNumber.setError("请输入购买份数！");
							return ;
						}
						if(number.length() > 7){
							etNumber.setError("最多可以购买" + (int)shengyu + "份！");
							return ;
						}
						if(Integer.parseInt(number) == 0){
							//Toast.makeText(context,  "请输入购买份数", 0).show();
							etNumber.setError("购买份数不能为0！");
							return ;
						}
						if(Integer.parseInt(number) > shengyu){
							etNumber.setError("最多可以购买" + (int)shengyu + "份！");
							return ;
						}
						mEtxtNum.setText(number);
						viewHolder.getTextView(R.id.txt_price).setText(number);
						item.setCount(Integer.parseInt(number));
						// Toast.makeText(context, item.getCount() + "",
						// Toast.LENGTH_SHORT).show();
						cartProvider.update(item);
						showTotalPrice();
						carNumberDialog.dismiss();
					}
					
					@Override
					public void doCancel() {
						// TODO Auto-generated method stub
						carNumberDialog.dismiss();
					}
				});
				
				/*Toast.makeText(context, value + " ", 0).show();
				mEtxtNum.setText(12+"");
				viewHolder.getTextView(R.id.txt_price).setText(12 + "");
				item.setCount(12);
				// Toast.makeText(context, item.getCount() + "",
				// Toast.LENGTH_SHORT).show();
				cartProvider.update(item);
				showTotalPrice();*/
			}
			
			
		});

		if (!EmptyUtil.isEmpty(OApi.uid)) {
			uid = OApi.uid;
		} else {
			uid = PrefUtils.getString(context, "userId", "1");
		}

		ll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Toast.makeText(context, "点击" + datas.size(),
				// Toast.LENGTH_SHORT).show();
				
				if(PrefUtils.getBoolean(context, "isLogin", false)){
					int size = datas.size();
					if(size == 0){
						Toast.makeText(context, "购物车为空哦，请先选购商品", 0).show();
						return ;
					}
					try {
						JSONObject check = new JSONObject();
						JSONObject buy_money = new JSONObject();
						for (int i = 0; i < size; i++) {
								String id = datas.get(i).getId();
								int count = datas.get(i).getCount();
								check.put("" + i, id);
								buy_money.put(id, count + "");
						}
						final JSONObject obj = new JSONObject();
						JSONObject info = new JSONObject();
						info.put("check", check);
						info.put("buy_money", buy_money);
						info.put("uid", uid);
						obj.put("path", "/Home/Buyrecord/appBuy");
						obj.put("info", info);
						/*
						 * {"path":"\/Home\/Buyrecord\/appBuy","info":{"check":{"1":
						 * "8","0":"7"},"buy_money":{"7":"1","8":"2"}}}
						 * 
						 */

						if (!EmptyUtil.isEmpty(uid)) {
							//checkAll_None(true);
							RequestParams params = new RequestParams();
							try {
								params.setBodyEntity(new StringEntity(obj.toString(), "utf-8"));
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							HttpUtils utils = new HttpUtils();
							utils.send(HttpMethod.POST, OApi.Public_appBuy, params, new RequestCallBack<String>() {

								@Override
								public void onFailure(HttpException arg0,
										String arg1) {
									// TODO Auto-generated method stub
									Toast.makeText(context, arg1, 0).show();
								}

								@Override
								public void onSuccess(ResponseInfo<String> arg0) {
									// TODO Auto-generated method stub
									Gson gson  = new Gson();
									String result = arg0.result;
									try {
										JSONObject json = new JSONObject(result);
										if(json.getInt("status") == 0){
											Toast.makeText(context, json.getString("data"), 0).show();
										}
										if(json.getInt("status") == 1){
											Intent i = new Intent(context,PayActivity.class);
											 i.putExtra("info", obj.toString());
											 context.startActivity(i);
										}
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							});
							 
							 //i.putParcelableArrayListExtra("datas", (ArrayList<? extends Parcelable>) datas);
							// ((FragmentActivity) context).startActivityForResult(i, 0);
						} else {
							Intent i = new Intent(context, LoginActivity.class);
							i.putExtra("isFrom", 1);
							context.startActivity(i);
						}

						 JLog.i("CartAdapter", obj.toString());

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}else{
					context.startActivity(new Intent(context, LoginActivity.class));
				}
				
			}
		});
	}

	public void setCheckBox(CheckBox ck) {
		this.checkBox = ck;
		checkBox.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				checkAll_None(checkBox.isChecked());
			}
		});
	}

	private boolean isNull() {
		return (datas != null && datas.size() > 0);
	}

	public void checkAll_None(boolean isChecked) {
		if (!isNull())
			return;

		int i = 0;
		for (ShoppingCart cart : datas) {
			cart.setIsChecked(isChecked);
			notifyItemChanged(i);
			i++;
		}
	}

	public void setTextView(TextView textView) {
		this.total_price = textView;
	}

	private float getTotalPrice() {
		int sum = 0;
		if (!isNull())
			return sum;

		for (ShoppingCart cart : datas) {
			//if (cart.isChecked())
				sum += cart.getCount() * 1.00;
		}
		return sum;
	}

	public void showTotalPrice() {
		float total = getTotalPrice();
		total_price.setText("￥" + total + "");
		goods_counts.setText(Values.idList.size() + "");
		if(total == 0){
			cfragshop_null.setVisibility(View.VISIBLE);
		}else{
			cfragshop_null.setVisibility(View.GONE);
		}
	}

	@Override
	public void onItemClick(View view, int position) {
		ShoppingCart cart = getItem(position);
		cart.setIsChecked(!cart.isChecked());
		notifyItemChanged(position);

		checkListen();
		showTotalPrice();
	}

	public void delCart() {
		if (!isNull())
			return;

		for (Iterator<ShoppingCart> iterator = datas.iterator(); iterator.hasNext();) {

			ShoppingCart cart = (ShoppingCart) iterator.next();
			if (cart.isChecked()) {
				int position = datas.indexOf(cart);
				cartProvider.delete(cart);
				iterator.remove();
				notifyItemRemoved(position);
			}

		}
		notifyDataSetChanged();
		showTotalPrice();
	}
	
	public void delCart2(ShoppingCart cart) {
		if (!isNull())
			return;

		for (Iterator<ShoppingCart> iterator = datas.iterator(); iterator.hasNext();) {
				int position = datas.indexOf(cart);
				cartProvider.delete(cart);
				iterator.remove();
				notifyItemRemoved(position);
		}
		notifyDataSetChanged();
		showTotalPrice();
	}
	
	public void delAllCart() {
		if (!isNull())
			return;

		Toast.makeText(context, "fasdf", 0).show();
		for (Iterator<ShoppingCart> iterator = datas.iterator(); iterator.hasNext();) {

			ShoppingCart cart = (ShoppingCart) iterator.next();
				int position = datas.indexOf(cart);
				cartProvider.delete(cart);
				iterator.remove();
				notifyItemRemoved(position);
		}
		notifyDataSetChanged();
		showTotalPrice();
	}

	private void checkListen() {
		int count = 0;
		int checkNum = 0;
		if (datas != null) {
			count = datas.size();
			for (ShoppingCart cart : datas) {
				if (!cart.isChecked()) {
					checkBox.setChecked(false);
					break;
				} else {
					checkNum = checkNum + 1;
				}
			}

			if (count == checkNum) {
				checkBox.setChecked(true);
			}
		}
	}
	
	protected void addShoppingCart(String goods_id, String expect, final ShoppingCart entity,final int value,final BaseRViewHolder viewHolder,final TextView mEtxtNum,final int shengyu) {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		try {
			json.put("app", "1");
			json.put("model", "BuyRecord");
			json.put("function", "addCarList");
			json.put("code", goods_id + "," + expect );
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestParams params = new RequestParams();
		try {
			params.setBodyEntity(new StringEntity(json.toString(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block   
			e.printStackTrace();
		}
		HttpUtils utils = new HttpUtils();
		if(Values.cookieStore == null){
		DefaultHttpClient httpClient = (DefaultHttpClient) utils.getHttpClient();
		Values.cookieStore = httpClient.getCookieStore();
		}else{
			utils.configCookieStore(Values.cookieStore);
		}
		utils.send(HttpMethod.POST, OApi.Public_appPort, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				Toast.makeText(context, arg1, 0).show();
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String result = arg0.result;
				try {
					JSONObject jso = new JSONObject(result);
					int status = jso.getInt("status");
					//Toast.makeText(mContext, "status=" + status + "\ndata=" + jso.getString("data"), 0).show();
					if(status == 0){
						Toast.makeText(context, jso.getString("data"), 0).show();
						mEtxtNum.setText(viewHolder.getTextView(R.id.txt_price).getText().toString());
						return ;
					}
					if(status == 1){
						if(Integer.parseInt(viewHolder.getTextView(R.id.txt_price).getText().toString()) >= shengyu){
							Toast.makeText(context, "最多只能购买" + shengyu + "份", 0).show();
						}else{
							viewHolder.getTextView(R.id.txt_price).setText(value + "");
							//Toast.makeText(context, "已添加到购物车！", 0).show();
							entity.setCount(value);
							cartProvider.update(entity);
							showTotalPrice();
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

}
